<template>
  <main class="show_main">
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home/post' }" style="font-weight:500;">首页</el-breadcrumb-item>
      <el-breadcrumb-item>{{collegeName}}</el-breadcrumb-item>
      <el-breadcrumb-item>{{postType}}</el-breadcrumb-item>
    </el-breadcrumb>
    <div class="post">
      <div class="title">{{postinfo.title}}</div>
      <div class="author">
        <router-link
          tag="a"
          :to="{path:postinfo.publisher===username?'/usercenter':'/centerT',query:{id:postinfo.publisher}}"
        >
          <el-avatar size="small" :src="postinfo.imgUrl" style="margin-right:5px;"></el-avatar>
        </router-link>
        {{postinfo.publisher}}发布于{{postinfo.pubDate}}&nbsp;·&nbsp;浏览：{{postinfo.readCount}}&nbsp;回复：{{comments.length}}
      </div>
      <div class="content">{{postinfo.content}}</div>
      <el-divider></el-divider>
      <div class="star">
        <i :class="starCl" @click="is_star=!is_star"></i>
        <span>点赞({{postinfo.praiseCount}})</span>
        <i class="el-icon-chat-line-square" @click="commentClick"></i>
        <span>评论({{postinfo.commentCount}})</span>
      </div>
    </div>
    <div class="commentList">
      <div class="count">共{{comments.length}}条评论</div>
      <Comment v-for="(item,index) in comments" :key="index" :item="item" :username="username"></Comment>
    </div>
    <div class="comment">
      <el-input
        type="textarea"
        placeholder="请输入内容"
        v-model="commentContent"
        maxlength="100"
        show-word-limit
        style="width:100%;"
        rows="5"
        ref="commentInput"
      ></el-input>
      <el-button
        type="primary"
        style="margin-top:20px;"
        :disabled="commentBtn"
        @click="sendComment"
      >提交评论</el-button>
    </div>
  </main>
</template>
<script>
import Comment from './comment.vue'
export default {
  props: ['username'],
  data() {
    return {
      postId: '', // 帖子的id
      commentContent: '', // 评论提交内容
      commentBtn: true, // 评论提交按钮
      postinfo: '', // 帖子内容
      starCl: 'iconfont icon-dianzan', // 点赞的样式
      is_star: '', // 帖子点赞
      star_sign: '', // 初始点赞的状态
      comments: [], // 所有评论内容
      collegeName: '',
      postType: ''
    }
  },
  created() {
    this.collegeName = window.sessionStorage.getItem('collegeName')
    this.postType =
      window.sessionStorage.getItem('postType') === 'all'
        ? '全部帖子'
        : '精华帖'
    // 得到post的id
    this.postId = this.$route.query.id
    // 得到内容
    this.getappointPost(this.postId).then(() => {
      this.postinfo.readCount++
      // 判断此用户是否点过赞
      // console.log('==========')
      // console.log(this.postinfo.praiseCount)
      var praiseCount = this.postinfo.praisePerson.length
      this.postinfo.praiseCount = praiseCount
      if (praiseCount) {
        var index = this.postinfo.praisePerson.findIndex(i => {
          return i === this.username
        })
        this.is_star = index !== -1 ? true : false
        this.star_sign = index !== -1 ? true : false
      } else {
        this.is_star = false
        this.star_sign = false
      }
      // 增加阅读量
      this.updatePost('readCount')
    })
  },
  methods: {
    // 得到帖子内容
    async getappointPost(id) {
      const postRes = await this.$http.get('/getappointPost/' + id)
      if (postRes.meta.status !== 200) {
        return this.$Message.error('获取帖子信息失败')
      }
      var postData = postRes.data
      // 获取发帖者头像
      await this.comm.getuserImg(postData.publisher).then(data => {
        postData.imgUrl = data
      })
      this.postinfo = postData
      const comRes = await this.$http.get('/getcomment', {
        params: {
          type: 'show',
          id: id
        }
      })
      if (comRes.meta.status !== 200) {
        return this.$Message.error('获取评论失败')
      }
      // console.log(comRes)
      this.comments = comRes.data.reverse()
    },
    // comment获得焦点
    commentClick() {
      this.$refs.commentInput.focus()
    },
    // 增加阅读量、点赞量
    async updatePost(option, praisePerson) {
      const res = await this.$http.post('/updatePost/', {
        _id: this.postId,
        msg: option,
        [praisePerson]: this.username,
        type: 'content'
      })
      if (res.meta.status !== 200) {
        return this.$Message.error('服务器出现错误')
      }
      if (option === 'praiseCountAdd' || option === 'praiseCountRed') {
        var noticeMsg =
          option === 'praiseCountAdd' ? '点赞你的帖子' : '取消点赞你的帖子'
        var integ = option === 'praiseCountAdd' ? 1 : -1
        this.comm
          .editInteg(
            this.postinfo.publisher,
            'integ.parise',
            integ,
            this.username,
            noticeMsg,
            this.postId
          )
          .then(data => {
            if (!data) {
              return this.$Message.error('服务器出错！')
            }
          })
      }
    },
    // 提交评论
    async sendComment() {
      const res = await this.$http.post('/sendComment', {
        postId: this.postId,
        commentator: this.username,
        content: this.commentContent,
        commDate: this.comm.timeFilter()
      })
      if (res.meta.status !== 200) {
        return this.$Message.error('评论操作失败')
      }
      this.comm
        .editInteg(
          this.postinfo.publisher,
          'integ.comment',
          1,
          this.username,
          '评论了帖子 积分+1',
          this.postId
        )
        .then(data => {
          if (!data) {
            return this.$Message.error('服务器出错')
          }
          this.$Message.success('评论成功')
          this.comments.unshift({
            commentator: this.username,
            content: this.commentContent,
            commDate: this.comm.timeFilter()
          })
          this.content = ''
        })
    }
  },
  components: {
    Comment
  },
  watch: {
    // 监控评论框的内容，改变按钮的disabled
    commentContent: function(val) {
      this.commentBtn = val.trim().length ? false : true
    },
    // 监控点赞的变化
    is_star: function(val, oval) {
      this.starCl = val
        ? 'iconfont icon-dianzan starOn'
        : 'iconfont icon-dianzan'
      if (oval !== '') {
        this.postinfo.praiseCount = val
          ? this.postinfo.praiseCount + 1
          : this.postinfo.praiseCount - 1
      }
    }
  },
  // 实例销毁前调用
  beforeDestroy() {
    // 判断点赞的变化，如果改变则发起请求
    if (this.is_star !== this.star_sign) {
      // 点赞时加量，加姓名
      if (this.is_star) {
        return this.updatePost('praiseCountAdd', 'praisePerson')
      }
      // 取消点赞，减量，减姓名
      this.updatePost('praiseCountRed', 'praisePerson')
    }
  }
}
</script>
<style lang="less" scoped>
.home_container {
  width: 100%;
  background-color: #fafafc;
  .show_main {
    margin: 25px auto;
    width: 94%;
    min-height: 700px;
    .post {
      width: 70%;
      min-height: 200px;
      margin: 15px 0;
      padding: 20px;
      background-color: #fff;
      .title {
        font-size: 28px;
      }
      .author {
        display: flex;
        justify-content: left;
        align-items: center;
        margin: 10px 0;
        font-size: 12px;
        color: #8e94ab;
      }
      .content {
        width: 100%;
        min-height: 70px;
      }
      .star {
        display: flex;
        align-items: center;
        width: 100%;
        min-height: 30px;
        font-size: 14px;
        i {
          font-size: 24px;
          cursor: pointer;
        }
        span {
          margin-right: 20px;
        }
      }
    }
    .commentList {
      width: 70%;
      padding: 20px 20px;
      margin-bottom: 10px;
      background-color: #fff;
      .count {
        margin-bottom: 10px;
        font-size: 14px;
        color: #8e94ab;
      }
    }
    .comment {
      width: 70%;
      height: 300px;
      padding: 20px;
      background-color: #fff;
    }
  }
}
.starOn {
  color: red;
}
</style>
